package com.solution.pc.product.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.home.entity.SiteConfigItemEntity;
import com.solution.admin.home.service.SiteConfigItemService;
import com.solution.admin.product.constants.ProductConstants;
import com.solution.admin.product.entity.ProductBrandEntity;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductCategoryPropertyFilterEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductImageEntity;
import com.solution.admin.product.entity.ProductPriceEntity;
import com.solution.admin.product.entity.ProductPropertyEntity;
import com.solution.admin.product.entity.ProductPropertyRelaEntity;
import com.solution.admin.product.entity.ProductSpecCompositionEntity;
import com.solution.admin.product.entity.ProductSpecRelaEntity;
import com.solution.admin.product.service.ProductBrandService;
import com.solution.admin.product.service.ProductCategoryBrandService;
import com.solution.admin.product.service.ProductCategoryPropertyFilterService;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductImageService;
import com.solution.admin.product.service.ProductPriceService;
import com.solution.admin.product.service.ProductPropertyRelaService;
import com.solution.admin.product.service.ProductService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.service.OrderEvaluationService;
import com.solution.pc.product.entity.ProductSearchFilterEntity;
import com.solution.wx.my.service.UserFavoriteService;
import com.solution.wx.product.service.ProductBrowseRecordService;

/**
 * PC端商品查询控制层
 * 
 * @author llp
 */
@RequestMapping("/pc/product")
@Controller
public class ProductSearchController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ProductSearchController.class);
	
	@Autowired
	private ProductBrandService productBrandService;

	@Autowired
	private ProductCategoryPropertyFilterService productCategoryPropertyFilterService;

	@Autowired
	private ProductCategoryService productCategoryService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProductPriceService productPriceService;

	@Autowired
	private ProductPropertyRelaService productPropertyRelaService;

	@Autowired
	private ProductImageService productImageService;

	@Autowired
	private SiteConfigItemService siteConfigItemService;

	@Autowired
	private OrderEvaluationService orderEvaluationService;

	@Autowired
	private UserFavoriteService userFavoriteService;

	@Autowired
	private ProductBrowseRecordService productBrowseRecordService;
	
	@Autowired
	ProductCategoryBrandService productCategoryBrandService;

	/**
	 * PC端商品列表搜索
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/search")
	public String listProductListPage(HttpServletRequest request, Model model) {
		// 组装查询条件，用于页面显示已经选择的筛选项
		List<ProductSearchFilterEntity> filterNameList = new ArrayList<ProductSearchFilterEntity>();
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 商品分类（单个商品分类进来的话，还是把它当成第一种）
		String productCategoryId = request.getParameter("categoryId");
		// 搜索关键字（根据商品分类查询）
		String productSearchKey = null != request.getParameter("searchKey") ? request.getParameter("searchKey").trim() : null;
		// 解决以GET方式提交的中文乱码
		try {
			if (request.getMethod().toUpperCase().equals("GET") && null != productSearchKey) {
				productSearchKey = new String(productSearchKey.getBytes("ISO-8859-1"), "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		// 品牌
		String brandId = request.getParameter("brandId");
		String brandIds = request.getParameter("brandIds");
		// 如果条件品牌是单个，就把多个删除
		if(StringUtil.isNotNull(brandId)) {
			brandIds = null;
		}
		// 筛选项查询条件
		String propertyFilter = request.getParameter("propertyFilter");
		// 价格(最低价-最高价)
		String minPrice = request.getParameter("minPrice");
		String maxPrice = request.getParameter("maxPrice");
		// 排序相关
		String sortField = request.getParameter("sortField");
		if (StringUtil.isEmpty(sortField)) {
			sortField = "SORT_NO";
		}
		String sortType = request.getParameter("sortType");
		if (StringUtil.isEmpty(sortType)) {
			sortType = " ASC ";
		}
		// 商品标签
		String productTag = request.getParameter("productTag");
		
		
		
		try {
			/** 2、初始化页面的数据（商品分类） */
			List<ProductCategoryEntity> topCategoryList = initProductCategoryData();
			model.addAttribute("topCategoryList", topCategoryList);
			/**
			 * 3、先拿到所有的查询参数，查询到对应商品列表<br>
			 * 查询类型一般分3种<br>
			 * 1、选中多个分类进行搜索<br>
			 * 2、输入关键字搜索（商品名称、商品关键字）带出所有商品的类型集合<br>
			 * 3、全部商品检索（无关键字、无类型）<br>
			 * */
			/* 第一种 */
			// 组装页面显示所需要的商品分类
			List<Long> categoryIdList = new ArrayList<Long>();
			if (StringUtil.isNotNull(productCategoryId)) {
				// 有逗号分隔，说明是多个分类，不需要查询子分类
				if (productCategoryId.contains(",")) {
					String[] categoryIdArr = productCategoryId.split(",");
					for (String categoryId : categoryIdArr) {
						categoryIdList.add(Long.parseLong(categoryId));
					}
					param.put("categoryIdList", categoryIdList);
					param.put("status", 1);
					param.put("isDelete", 1);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					if (null != categoryList && categoryList.size() > 0) {
						String value = "";
						for (ProductCategoryEntity productCategory : categoryList) {
							value += productCategory.getCategoryName() + "、";
						}
						value = value.substring(0, value.length() - 1);
						filterNameList.add(new ProductSearchFilterEntity("v_categoryId", "类型", value));
					}
					model.addAttribute("categoryList", categoryList);
				} else {
					param.put("parentCategoryId", productCategoryId);
					param.put("status", 1);
					param.put("isDelete", 1);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					categoryIdList.add(Long.parseLong(productCategoryId));
					ProductCategoryEntity pce = productCategoryService.getProductCategoryById(Long.parseLong(productCategoryId));
					filterNameList.add(new ProductSearchFilterEntity("v_categoryId", "类型", pce.getCategoryName()));
					// 如果没有子分类，那就还是显示它自己吧
					if (null == categoryList || categoryList.size() == 0) {
						categoryList.add(pce);
					}
					model.addAttribute("categoryList", categoryList);
				}
			}
			// 第二种
			param.put("searchKey", productSearchKey);
			
			// 4、组装参数并执行商品查询
			// 筛选项查询条件
			if (StringUtil.isNotEmpty(propertyFilter)) {
				List<ProductPropertyEntity> propertyList = JSONArray.parseArray(propertyFilter, ProductPropertyEntity.class);
				// 添加页面筛选条件
				for (ProductPropertyEntity property : propertyList) {
					filterNameList.add(new ProductSearchFilterEntity("v_propertyFilter", property.getPropertyName(), property.getPropertyValue()));
				}
				param.put("propertyList", propertyList);
			} else {
				param.put("propertyList", Collections.EMPTY_LIST);
			}
			// 品牌
			param.put("brandId", brandId);
			if (StringUtil.isNotEmpty(brandIds)) {
				param.put("brandIds", "(" + brandIds + ")");
			}
			// 价格(最低价-最高价)
			param.put("minPrice", minPrice);
			param.put("maxPrice", maxPrice);
			model.addAttribute("filterNameList", filterNameList);
			// 商品类型ids 查询参数
			StringBuffer categoryIds = new StringBuffer("(");
			// 用于查询商品的分类合集
			StringBuffer productCategoryIds = new StringBuffer("(");
			if (null != categoryIdList && categoryIdList.size() > 0) {
				if(categoryIdList.size() == 1) {
					// 获取其所有的子集
					categoryIds.append(categoryIdList.get(0)).append(",");
					productCategoryIds.append(categoryIdList.get(0)).append(",");
					Map<String, Object> categoryParam = new HashMap<String, Object>();
					categoryParam.put("parentCategoryId", categoryIdList.get(0));
					List<ProductCategoryEntity> childCategoryList = productCategoryService.listProductCategory(categoryParam);
					if(null != childCategoryList && childCategoryList.size() > 0) {
						for (ProductCategoryEntity pc : childCategoryList) {
							productCategoryIds.append(pc.getId()).append(",");
                        }
					}
				} else {
					for (Long categoryId : categoryIdList) {
						categoryIds.append(categoryId).append(",");
						productCategoryIds.append(categoryId).append(",");
					}
				}
				categoryIds = new StringBuffer(categoryIds.substring(0, categoryIds.length() - 1)).append(")");
				productCategoryIds = new StringBuffer(productCategoryIds.substring(0, productCategoryIds.length() - 1)).append(")");
			}
			param.put("categoryIds", categoryIds);
			// 排序
			param.put("sortField", sortField);
			param.put("sortType", sortType);
			
			// 【关键字查询】查询商品列表（模糊匹配商品名称 or 类型名称 or 品牌名称）
			// 【筛选项】品牌查询|类型查询|筛选项查询
			PageParam pageParam = super.getPageParam(request, 20);
			param.put("customerLevel", getCustomerLevel());
			param.put("isLogin", isLogin(request) ? "1" : "0");
			param.put("customerId", getCustomerId());
			param.put("searchKey", productSearchKey);
			param.put("productTag", productTag);
			param.put("categoryIds", productCategoryIds.length() < 3 ? null : productCategoryIds.toString());
			PageBean pageBean = productService.listProductPageForIndex(pageParam, param);
			model.addAttribute("productList", pageBean.getRecordList());
			model.addAttribute("pageBean", pageBean);
			
			//其他的分类
			param.put("categoryIds", categoryIds.length() < 3 ? null : categoryIds.toString());
			
			/**
			 * 5、查询完成，获取页面条件品牌
			 * */
			/* 查询商品属性、查询品牌，就可以用父级分类去查询 */
			// T1、开始获取品牌列表
			List<ProductBrandEntity> brandList = null;
			// 搜索相关品牌
			brandList = productBrandService.listAllBrandForIndex(param);
			// 分类如果没关联，那就再去附近看下
			if (null == brandList || brandList.size() == 0) {
				// 如果没获取到，那就取其父级分类
				param.put("categoryIdList", categoryIdList);
				List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
				// 商品类型ids 查询参数
				StringBuffer categoryIdString = new StringBuffer("(");
				for (ProductCategoryEntity productCategory : categoryList) {
					if (null != categoryList && categoryList.size() > 0) {
						categoryIdString.append(productCategory.getParentCategoryId()).append(",").append(productCategory.getId()).append(",");
					}
				}
				categoryIdString = new StringBuffer(categoryIdString.substring(0, categoryIdString.length() - 1)).append(")");
				param.put("categoryIds", categoryIdString.length() < 3 ? null : categoryIdString.toString());
				brandList = productBrandService.listAllBrandForIndex(param);
				// 还原子分类
				param.put("categoryIds", categoryIds.length() < 3 ? null : categoryIds.toString());
			}
			model.addAttribute("brandList", brandList);
			// T2、品牌处理
			// key-value = brand_id-brand_name 方面页面显示品牌名称
			Map<Long, String> brandNameMap = new HashMap<Long, String>();
			// 处理品牌的分类，根据首字符中进行A~Z分类存在到List,到页面中循环展示
			Map<String, List<ProductBrandEntity>> brandMap = new HashMap<String, List<ProductBrandEntity>>();
			if (brandList != null && brandList.size() > 0) {
				for (ProductBrandEntity brand : brandList) {
					brandNameMap.put(brand.getId(), brand.getBrandNameCh());
					if (StringUtil.isNotNull(brand.getBrandLetterFrist())) {
						String key = brand.getBrandLetterFrist().substring(0, 1).toUpperCase();
						if (brandMap.containsKey(key)) {
							List<ProductBrandEntity> tmpBrandList = brandMap.get(key);
							tmpBrandList.add(brand);
						} else {
							List<ProductBrandEntity> tmpBrandList = new ArrayList<ProductBrandEntity>();
							tmpBrandList.add(brand);
							brandMap.put(key, tmpBrandList);
						}
					}
				}
			}
			List<List<ProductBrandEntity>> showBrandList = new ArrayList<List<ProductBrandEntity>>();
			for (char c = 'A'; c <= 'Z'; c++) {
				if (brandMap.containsKey(String.valueOf(c))) {
					showBrandList.add(brandMap.get(String.valueOf(c)));
				} else {
					showBrandList.add(Collections.EMPTY_LIST);
				}
			}
			model.addAttribute("showBrandList", showBrandList);
			// 排序规则（综合（指定）、人气（浏览次数）、新品（审核时间？？）、价格（基价））
			// 添加筛选条件
			if (StringUtil.isNotEmpty(brandId) && brandNameMap.containsKey(Long.parseLong(brandId))) {
				filterNameList.add(new ProductSearchFilterEntity("v_brandId", "品牌", brandNameMap.get(Long.parseLong(brandId))));
			}
			if (StringUtil.isNotEmpty(brandIds)) {
				// 添加筛选条件
				StringBuffer brandBuf = new StringBuffer();
				String[] brandIdStrArr = brandIds.split(",");
				for (int i = 0; i < brandIdStrArr.length; i ++) {
					String brandName = brandNameMap.get(Long.parseLong(brandIdStrArr[i]));
					if(StringUtil.isNotNull(brandName)) {
						brandBuf.append(brandName).append("、");
					}
				}
				if (StringUtil.isNotEmpty(brandBuf)) {
					filterNameList.add(new ProductSearchFilterEntity("v_brandIds", "品牌", brandBuf.substring(0, brandBuf.length() - 1)));
				}
			}

			/**
			 * 6、商品属性筛选项
			 * */
			boolean isAll = false;
			if (StringUtil.isEmpty(productCategoryId) && StringUtil.isEmpty(productSearchKey)) {
				// 无商品分类参数、无商品关键字参数，则查询所有商品
				// 商品分类则显示
				isAll = true;
				// 查询所有一级分类
				param.put("parentCategoryId", 0);
				param.put("status", 1);
				param.put("isDelete", 1);
				List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
				model.addAttribute("categoryList", categoryList);
			} else if (StringUtil.isNotNull(productSearchKey) && StringUtil.isEmpty(productCategoryId)) {
				// 有关键字参数，没有商品分类参数
				// 那么商品分类则汇总所有已查询到的商品
				param.put("productName", productSearchKey);
				param.put("normalPro", "1");// 正常商品，过滤掉已下架商品
				param.put("brandCode", brandId);
				List<ProductEntity> proList = productService.listProduct(param);
				for (ProductEntity product : proList) {
					categoryIdList.add(product.getProductCategoryId());
				}
				param.put("categoryIdList", categoryIdList);
				if (categoryIdList.size() > 0) {
					param.put("status", 1);
					param.put("isDelete", 1);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					List<ProductCategoryEntity> opCategoryList = new ArrayList<ProductCategoryEntity>();
					for (ProductCategoryEntity productCategory : categoryList) {
						// 如果是一级分类，则去掉，理论上只保留二级分类
						int length = productCategory.getPath().length() - productCategory.getPath().replaceAll("\\|", "").length();
						if (length == 1) {
							// 一级分类
						}
						if (length == 2) {
							opCategoryList.add(productCategory);
						}
					}
					model.addAttribute("categoryList", opCategoryList);
				}
			}
			if (!isAll) {
				// 根据商品分类去获取属性筛选项
				List<ProductCategoryPropertyFilterEntity> filterList = null;
				if ((null == filterList || filterList.size() == 0) && categoryIdList.size() > 0) {
					filterList = productCategoryPropertyFilterService.listProductCategoryPropertyFilterForIndex(param);
					// 如果没获取到，那就取其父级分类
					param.remove("parentCategoryId");
					param.put("categoryIdList", categoryIdList);
					List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategory(param);
					// 商品类型ids 查询参数
					if (null != categoryList && categoryList.size() > 0) {
						StringBuffer categoryIdString = new StringBuffer("(");
						for (ProductCategoryEntity productCategory : categoryList) {
							categoryIdString.append(productCategory.getParentCategoryId()).append(",").append(productCategory.getId()).append(",");
						}
						categoryIdString = new StringBuffer(categoryIdString.substring(0, categoryIdString.length() - 1)).append(")");
						// param.put("categoryIds", StringUtil.isNotEmpty(categoryIdString) ? categoryIdString.toString() : null);
						param.put("categoryIds", categoryIdString.length() < 3 ? null : categoryIdString.toString());
						filterList = productCategoryPropertyFilterService.listProductCategoryPropertyFilterForIndex(param);
						// 还原子分类
						// param.put("categoryIds", StringUtil.isNotEmpty(categoryIds) ? categoryIds.toString() : null);
						param.put("categoryIds", categoryIds.length() < 3 ? null : categoryIds.toString());
					}
				}
				if (filterList != null && filterList.size() > 0) {
					for (ProductCategoryPropertyFilterEntity filter : filterList) {
						if (StringUtil.isNotEmpty(filter.getPropertyValue())) {
							String[] pvs = filter.getPropertyValue().split(",");
							List<String> tmpList = new ArrayList<>();
							for (String pv : pvs) {
								tmpList.add(pv);
							}
							filter.setPropertyValueList(tmpList);
						}
					}
				}
				model.addAttribute("filterList", filterList);
			}
			// 价格
			if (StringUtil.isNotEmpty(minPrice)) {
				if ("999999999".equals(minPrice)) {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", minPrice + "元以上"));
				} else {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", minPrice + "~" + maxPrice));
				}
			} else {
				if (StringUtil.isNotEmpty(minPrice) && !"999999999".equals(minPrice)) {
					filterNameList.add(new ProductSearchFilterEntity("v_price", "价格", maxPrice + "元以下"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/** 1.为页面赋予初始化数据 */
		model.addAttribute("searchKey", productSearchKey);
		model.addAttribute("categoryId", productCategoryId);
		model.addAttribute("brandId", brandId);
		model.addAttribute("brandIds", brandIds);
		model.addAttribute("sortField", sortField);
		model.addAttribute("sortType", sortType);
		model.addAttribute("minPrice", minPrice);
		model.addAttribute("maxPrice", maxPrice);
		model.addAttribute("propertyFilter", StringUtil.isNotEmpty(propertyFilter) ? propertyFilter.replace("\"", "'") : "");
		model.addAttribute("productTag", productTag);
		return "pc/product/product_list";
	}

	/**
	 * 初始化所有商品分类，建立从属关系
	 * 
	 * @return List<ProductCategoryEntity>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年1月29日 上午11:49:26
	 */
	private List<ProductCategoryEntity> initProductCategoryData() {
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 所有商品类型
		List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
		if (topCategoryList != null && topCategoryList.size() > 0) {
			for (ProductCategoryEntity category : topCategoryList) {
				// 获取此父级分类下所有 子分类对应的品牌列表
				List<ProductBrandEntity> subBrandList = productCategoryBrandService.getSubBrandList(category.getId());
				category.setSubBrandList(subBrandList);
				
				if (StringUtil.isNotEmpty(category.getSubCategoryListStr())) {
					List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("[" + category.getSubCategoryListStr() + "]",
					        ProductCategoryEntity.class);
					category.setSubCategoryList(tmpCategoryList);
				}
			}
		}
		return topCategoryList;
	}

	/**
	 * 搜索商品-商品列表页面
	 * 
	 * @param request
	 * @return
	 * @author llp
	 */
	@RequestMapping("/detail")
	public String findProductDetail(HttpServletRequest request, Model model) {
		String productId = request.getParameter("productId");
		// 查询参数
		Map<String, Object> param = new HashMap<String, Object>();
		// 【1】、查询所有商品类型
		List<ProductCategoryEntity> topCategoryList = productCategoryService.listProductCategoryForIndex(param);
		if (topCategoryList != null && topCategoryList.size() > 0) {
			for (ProductCategoryEntity category : topCategoryList) {
				// 获取此父级分类下所有 子分类对应的品牌列表
				List<ProductBrandEntity> subBrandList = productCategoryBrandService.getSubBrandList(category.getId());
				category.setSubBrandList(subBrandList);
				
				if (StringUtil.isNotEmpty(category.getSubCategoryListStr())) {
					List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("[" + category.getSubCategoryListStr() + "]",
					        ProductCategoryEntity.class);
					category.setSubCategoryList(tmpCategoryList);
				}
			}
		}
		request.setAttribute("topCategoryList", topCategoryList);

		Map<String, Object> productDetailMap = new HashMap<String, Object>();
		// 【2】查询商品信息
		param.put("productId", productId);
		/**
		 * key-object product_info 商品基本信息 product_price 商品所有价格 product_spec 商品规格
		 * product_composition 商品规格项组合 product_property 商品详情属性 produt_image 商品图片
		 * product_comment 商品评论
		 */
		ProductEntity product = productService.getProductById(Long.parseLong(productId));
		// 商品基本信息和详情
		productDetailMap.put("product_info", product);

		// 主商品价格 = 基价 + 客户差价
		BigDecimal productPrice = product.getBasePrice();
		BigDecimal marketProductPrice = product.getMarketPrice();

		// 【3】查询商品所有价格
		List<ProductPriceEntity> ppeList = productService.getProductPriceList(Long.parseLong(productId));
		productDetailMap.put("product_price", ppeList);
		String customerLevel = getCustomerLevel();
		if (isLogin(request)) {

			if (ppeList != null && ppeList.size() > 0) {
				for (ProductPriceEntity ppe : ppeList) {
					if (ppe.getPriceLevel().equals(customerLevel)) {
						productPrice = productPrice.add(ppe.getDiffPrice());
						marketProductPrice = marketProductPrice.add(ppe.getDiffPrice());
					}
				}
			}
		} else {
			// 匿名用户 显示游客价 和 市场价 + 对应的默认规格价格
			productPrice = (null != product.getTouristPrice()) ? product.getTouristPrice() : BigDecimal.ZERO;
			marketProductPrice = (null != product.getMarketPrice()) ? product.getMarketPrice() : BigDecimal.ZERO;
		}
		
		

		// 【4】查询商品规格(包裹规格项的名称、值、价格)
		List<ProductSpecRelaEntity> productSpecList = productService.listProductSpecPriceByProductId(param);
		BigDecimal defaultSpecPrice = new BigDecimal(0);
		if (productSpecList != null && productSpecList.size() > 0) {
			for (ProductSpecRelaEntity productSpec : productSpecList) {
				if (StringUtil.isNotEmpty(productSpec.getProductSpecListStr())) {
					List<ProductSpecRelaEntity> tmpSpecList = JSONArray.parseArray("[" + productSpec.getProductSpecListStr() + "]",
					        ProductSpecRelaEntity.class);
					productSpec.setProductSpecList(tmpSpecList);

					if (tmpSpecList != null && tmpSpecList.size() > 0) {
						defaultSpecPrice = defaultSpecPrice.add(tmpSpecList.get(0).getSpecPrice());
					}
				}
			}
		}

		// productPrice = 商品基本 + 客户级别差价
		// 主商品价格
		request.setAttribute("mainProductPrice", productPrice);
		request.setAttribute("mainMarketProductPrice", marketProductPrice);
		// 商品价格 基价+级别差价+默认规格价格
		request.setAttribute("productPrice", productPrice.add(defaultSpecPrice));
		request.setAttribute("marketProductPrice", marketProductPrice.add(defaultSpecPrice));

		productDetailMap.put("product_spec", productSpecList);

		// 【5】查询商品规格项组合
		List<ProductSpecCompositionEntity> productSpecCmpList = productService.listProductSpecCompostionByProductId(param);
		productDetailMap.put("product_composition", productSpecCmpList);

		// 【6】查询商品属性
		List<ProductPropertyRelaEntity> productPropertyList = productPropertyRelaService.listProductPropertyRela(Long.parseLong(productId));
		productDetailMap.put("product_property", productPropertyList);

		// 【7】查询商品图片
		List<ProductImageEntity> productImageList = productImageService.listProductImageForProductDetail(Long.parseLong(productId));
		if (productImageList != null && productImageList.size() > 0) {
			for (ProductImageEntity productImage : productImageList) {
				if (1 == productImage.getImageType()) {
					// 主图
					productDetailMap.put("product_main_image", productImage.getImagePath());
				}
			}
		}
		productDetailMap.put("product_image", productImageList);

		// 【8】查询热品采购
		// 热品采购商品列表
		List<ProductEntity> topProductList = new ArrayList<ProductEntity>();
		Map<String, Object> configParam = new HashMap<String, Object>();
		configParam.put("moduleId", "4");
		configParam.put("configType", "02");
		List<SiteConfigItemEntity> configList = siteConfigItemService.listSiteConfigItem(configParam);
		if (configList != null && configList.size() > 0) {
			for (SiteConfigItemEntity config : configList) {
				if (StringUtil.isNotEmpty(config.getProductCode())) {
					String[] tmpArr = config.getProductCode().split("##");
					ProductEntity productEntity = new ProductEntity();
					productEntity.setId(Long.parseLong(tmpArr[0]));
					System.out.println(","+productEntity.getId());
					productEntity.setProductName(tmpArr[1]);
					productEntity.setMainImagePath(tmpArr[2]);

					topProductList.add(productEntity);
				}
			}
		}
		List<ProductEntity> resultTopProductList = new ArrayList<ProductEntity>();
		for (ProductEntity productEntity : topProductList) {
			param.put("productId", productEntity.getId());
			ProductEntity tmpProduct = productService.getProductById(productEntity.getId());
			// 商品库中查不到的热品，直接过滤掉不显示
			if (tmpProduct != null && !ProductConstants.ProductStatus.STATUS_OFFLINE.equals(tmpProduct.getProductStatus())) {
				List<ProductPriceEntity> priceList = productPriceService.listProductPrice(param);
				if (priceList != null && priceList.size() > 0) {
					for (ProductPriceEntity ppe : priceList) {
						if (isLogin(request)) {
							if (ppe.getPriceLevel().equals(customerLevel)) {
								productEntity.setBasePrice(tmpProduct.getBasePrice().add(ppe.getDiffPrice()));
							}
						} else {
							// 如果未登录显示游客价
							productEntity.setBasePrice(tmpProduct.getTouristPrice());
						}
					}
				}
				
				if(productEntity.getBasePrice() == null){
					productEntity.setBasePrice(tmpProduct.getBasePrice());
				}
				resultTopProductList.add(productEntity);
			}
		}

		// 热销商品
		productService.initProductDefaultSpecPrice(resultTopProductList);
		request.setAttribute("topProductList", resultTopProductList);

		// 【9】查询推荐商品
		param.clear();
		param.put("productId", productId);
		param.put("isLogin", isLogin(request));
		param.put("customerLevel", getCustomerLevel());
		List<ProductEntity> realProductList = productService.listProductRelaList(param);
		request.setAttribute("realProductList", realProductList);

		// 查询商品的默认规格价格
		productService.initProductDefaultSpecPrice(realProductList);

		// 【9】查询商品类型路径
		List<ProductCategoryEntity> categoryPathList = new ArrayList<ProductCategoryEntity>();
		ProductCategoryEntity categoryEntity = productCategoryService.getProductCategoryById(product.getProductCategoryId());
		if (StringUtil.isNotEmpty(categoryEntity.getCategoryNamePath())) {
			String[] categoryIdArr = categoryEntity.getPath().split("\\|");
			String[] cateogryNameArr = categoryEntity.getCategoryNamePath().split("\\|");
			for (int i = 1; i < categoryIdArr.length; i++) {
				ProductCategoryEntity tmpCateogry = new ProductCategoryEntity();
				tmpCateogry.setId(Long.parseLong(categoryIdArr[i]));
				tmpCateogry.setCategoryName(cateogryNameArr[i - 1]);
				categoryPathList.add(tmpCateogry);
			}
		}
		request.setAttribute("categoryPathList", categoryPathList);

		// 商品详情
		request.setAttribute("productDetailMap", productDetailMap);

		// 商品是否被收藏
		if (isLogin(request)) {
			Long favoriteId = userFavoriteService.getCountByUserCodeAndProductId(getUserCode(), Long.parseLong(productId), null);
			request.setAttribute("favoriteId", favoriteId);
			// 加入足迹
			productBrowseRecordService.saveProductBrowseRecord(getUserCode(), Long.parseLong(productId));
		}
		return "pc/product/product_detail";
	}

	/**
	 * 异步查询商品评论
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2017年12月4日 上午10:20:42
	 */
	@RequestMapping("/queryProductEvaluation")
	@ResponseBody
	public Map<String, Object> queryProductEvaluation(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long productId = Long.parseLong(request.getParameter("productId"));
		PageParam pageParam = getPageParam(request);
		try {
			ProductEntity product = productService.getProductById(productId);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("productCode", product.getProductCode());
			paramMap.put("isDelete", 1);
			PageBean evaluationPage = orderEvaluationService.listOrderEvaluationPage(pageParam, paramMap);
			resultMap.put("evaluationPage", evaluationPage);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			handleException("查询评论失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 跳转至商品详情页面
	 * 
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月26日 上午10:30:35
	 */
	@RequestMapping("/toDetail")
	public String toDetail(HttpServletRequest request) {
		String productCode = request.getParameter("productCode");
		ProductEntity product = productService.getProductByCode(productCode);
		return "redirect:/pc/product/detail?productId=" + product.getId();
	}
}
